﻿using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Security.OAuth;
using Owin;
using SimpleInjector;
using SimpleInjector.Extensions.ExecutionContextScoping;
using Sustainalytics.Auth.Common;
using Sustainalytics.Auth.Service.Infrastructure;
using Sustainalytics.Auth.Service.OAuth;
using System;
using System.Collections.Generic;
using System.Configuration.Abstractions;
using System.Diagnostics.CodeAnalysis;

namespace Sustainalytics.Auth.Service
{
    [ExcludeFromCodeCoverage]
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var container = SimpleInjectorConfig.Register();
            using (container.BeginExecutionContextScope())
            {
                app.Use(typeof(LoggingMiddleware));
                var appSettings = container.GetInstance<IAppSettings>();
                var accessTokenExpireTimeSpan = appSettings.AppSetting<TimeSpan>("AccessTokenExpireTimeSpan");
                var allowInsecureHttp = appSettings.AppSettingSilent<bool>("AllowInsecureHttp", () => false);

                var allowCors = appSettings.AppSettingSilent("enableCors", () => false);
                if (allowCors)
                    app.UseCors(CorsOptions.AllowAll);

                var oAuthServerOptions = GetOAuthServerOptions(container, accessTokenExpireTimeSpan, allowInsecureHttp);
                app.UseOAuthAuthorizationServer(oAuthServerOptions);
            }
        }

        public static OAuthAuthorizationServerOptions GetOAuthServerOptions(Container container, TimeSpan accessTokenExpireTimeSpan, bool allowInsecureHttp)
        {
            return new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = allowInsecureHttp,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = accessTokenExpireTimeSpan,
                AccessTokenFormat = new CustomAccessTokenFormat(),
                Provider = container.GetInstance<CustomAuthorizationServerProvider>(),
                RefreshTokenProvider = container.GetInstance<CustomRefreshTokenProvider>(),
            };
        }
    }
}
